//
//  RegisterViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/22.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "RegisterViewController.h"
#import "UILabel+YBAttributeTextTapAction.h"
#import "LoginViewController.h"
#import "UserProtocalVC.h"
#import <Hyphenate/Hyphenate.h>
@interface RegisterViewController ()
{
    NSTimer *timer;//定时器
    int count;//记录时间
}
@property (weak, nonatomic) IBOutlet UITextField *timeTextField;

@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;//手机号
@property (weak, nonatomic) IBOutlet UITextField *invalideCodeTextField;//验证吗
@property (weak, nonatomic) IBOutlet UITextField *setPwdTextField;//设置密码
@property (weak, nonatomic) IBOutlet UITextField *confirmPwdTextField;//确认密码
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;//按钮下边的文字
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property(nonatomic,copy)NSString *code;
@end
@implementation RegisterViewController

- (void)viewDidLoad {
    self.vcName = @"注册";
    [super viewDidLoad];
    [self setLabelText];
    [self initRightBarItem];
    self.timeTextField.hidden = YES;
    self.timeTextField.enabled = NO;
    self.codeBtn.hidden = NO;
    self.phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.invalideCodeTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.setPwdTextField.secureTextEntry = YES;
    self.confirmPwdTextField.secureTextEntry = YES;

}

- (void)initRightBarItem{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame=CGRectMake(0, 0, 70, 40);
    [rightButton setTitle:@"登录" forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton setTitleColor:DEF_COLOR  forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    self.rightItem = rightButton;
}

-(void)rightAction{
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (IBAction)getCode:(UIButton *)sender {
    if(!self.phoneTextField.text.length) {
        [MBProgressHUD showTipMessageInWindow:@"请输入手机号码"];
        return;
    }
    if(![Tools isRightMobileNumber:self.phoneTextField.text]){
        [MBProgressHUD showErrorMessage:@"手机号码格式不正确"];
        return;
    }
    NSDictionary *paramDic = @{@"phoneNum":self.phoneTextField.text};
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:GETCODE paramters:paramDic afterResultBlock:^(NSDictionary *resultDic) {
        if([resultDic[@"flag"] isEqualToString:@"true"]){
             [MBProgressHUD showTipMessageInWindow:@"验证码发送成功"];
            DLog(@"验证吗--%@",resultDic);
            //,59秒倒计时
            [weakSelf timer59Seconds];
            NSDictionary *dataDic = resultDic[@"data"];
            weakSelf.code =dataDic[@"CAPTCHA"];
            [weakSelf.invalideCodeTextField becomeFirstResponder];
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

//4,59秒倒计时
- (void)timer59Seconds{
    self.codeBtn.hidden = YES;
    self.timeTextField.hidden = NO;
    if (!timer) {
        count = 59;
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeTime) userInfo:nil repeats:YES];
    }
}
- (void)changeTime{
    count--;
    self.timeTextField.text = [NSString stringWithFormat:@"%02d秒后可重新获取",count];
    if(count==0){
        [timer invalidate];
        timer = nil;
        self.codeBtn.hidden = NO;
        [self.codeBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        self.timeTextField.hidden = YES;
    }
}

- (IBAction)register:(UIButton *)sender {
    
    NSString *phone = self.phoneTextField.text;
    if(!phone.length){
        [MBProgressHUD showErrorMessage:@"请输入手机号码"];
        return;
    }
    if(![Tools isRightMobileNumber:phone]){
        [MBProgressHUD showErrorMessage:@"手机号码格式不正确"];
        return;
    }
    if(!self.invalideCodeTextField.text.length){
        [MBProgressHUD showTipMessageInWindow:@"请输入验证码"];
        return;
    }
    if(![self.invalideCodeTextField.text isEqualToString:self.code]){
        [MBProgressHUD showErrorMessage:@"验证码错误"];
        return;
    }
    NSString *spassWord = self.setPwdTextField.text;
    if(!spassWord.length){
        [MBProgressHUD showTipMessageInWindow:@"请输入密码"];
        return;
    }
    if(spassWord.length<6||spassWord.length>16){
        [MBProgressHUD showErrorMessage:@"请确认密码长度6-16位"];
        return;
    }
    NSString *confirmPwd = self.confirmPwdTextField.text;
    if(!confirmPwd.length){
        [MBProgressHUD showTipMessageInWindow:@"请再次输入密码"];
        return;
    }
    if(![spassWord isEqualToString:confirmPwd]){
        [MBProgressHUD showTipMessageInWindow:@"两次密码输入不一致"];
        return;
    }
    //2.24用户注册接口
    NSDictionary *paraDic = @{
                              @"phone":phone,
                              @"passWord":spassWord,
                              @"userType":@"0"
                              };
    __weak typeof( self) weakSelf = self;
   [MBProgressHUD showLoadingGif];
    [Tools AFNetworkingRequestTypePostWithUrl:REGISTER paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"注册--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]){
                [MBProgressHUD dismissHUD];
                return ;
            }
            if([dataDic[@"status"] isEqualToString:@"true"]){
                 [MBProgressHUD dismissHUD];
                [MBProgressHUD  showSuccessMessage:@"恭喜您注册成功"];
                USERPHONE = phone;
                [weakSelf performSelector:@selector(rightAction) withObject:nil afterDelay:1];
            }else{
                [MBProgressHUD dismissHUD];
                if(dataDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                }
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}


- (void)setLabelText{
    NSString *str = @"已阅读并同意一下协议，接受免除或者限制责任、诉讼管辖约定等粗体下划线标示条款。";
    NSMutableAttributedString *attributedString2 = [[NSMutableAttributedString alloc]initWithString:str];
    [attributedString2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, str.length)];
    [attributedString2 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(11, 17)];
    [attributedString2 addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(11,17)];
    self.contentLabel.attributedText =attributedString2;
    [self.contentLabel yb_addAttributeTapActionWithStrings:@[@"接受免除或者限制责任、诉讼管辖约定"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
        NSString *message = [NSString stringWithFormat:@"点击了“%@”字符\nrange: %@\nindex: %ld",string,NSStringFromRange(range),index];
        UserProtocalVC *protocalVc = [[UserProtocalVC alloc]init];
        [self.navigationController  pushViewController:protocalVc animated:YES];
        DLog(@"%@",message);
    }];
    //设置是否有点击效果，默认是YES
    self.contentLabel.enabledTapEffect = NO;
}
- (IBAction)protocolAction:(id)sender {
    UserProtocalVC *protocalVc = [[UserProtocalVC alloc]init];
    [self.navigationController pushViewController:protocalVc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
